import { reactive, ref } from "vue";
import type {
  RuleInfo,
  RuleQueryParams,
  RuleScenariosInfo,
  SelectOption,
  FieldInfo,
  RuleConditionItemInfo,
  Operator,
} from "@/types";
import axios from "axios";
import { ElMessage } from "element-plus";

export default function () {
  let ruleInsertWindowsEnable = ref(false);
  let selectedConditionFieldWindowsEnable = ref(false);
  let ruleCurrentPage = ref(1);
  let rulePageSize = ref(10);
  let ruleScenariosInfo = reactive<RuleScenariosInfo>({
    id: "",
    scenariosKey: "",
    scenariosName: "",
    conditionModelName: "",
    resultModelName: "",
    description: "",
    isEnable: 0,
  });
  let ruleScenariosOptionList = reactive<SelectOption[]>([]);
  let operatorList = reactive<SelectOption[]>([]);
  let ruleQueryParams = reactive<RuleQueryParams>({
    ruleName: "",
    scenariosKey: "",
    isEnable: 0,
  });
  let insertRule = reactive<RuleInfo>({
    id: "",
    ruleName: "",
    scenariosKey: "",
    condtitonDetail: [
      {
        fieldKey: "",
        fieldName: "",
        fieldValueType: "",
        type: "",
        fieldBasicType: "",
        operator: "",
        targetValue: {
          valueType: "",
          single: {},
          range: {},
          list: {},
        },
      },
    ],
    resultDetail: [
      {
        fieldKey: "",
        fieldName: "",
        fieldValueType: "",
        targetValue: "",
      },
    ],
    resultAction: "",
    description: "",
    startEffecTime: new Date(),
    endEffecTime: new Date(),
    isEnable: 0,
  });
  let updateRule = reactive<RuleInfo>({
    id: "",
    ruleName: "",
    scenariosKey: "",
    condtitonDetail: [
      {
        fieldKey: "",
        fieldName: "",
        fieldValueType: "",
        type: "",
        fieldBasicType: "",
        operator: "",
        targetValue: {
          valueType: "",
          single: {},
          range: {},
          list: {},
        },
      },
    ],
    resultDetail: [
      {
        fieldKey: "",
        fieldName: "",
        fieldValueType: "",
        targetValue: "",
      },
    ],
    resultAction: "",
    description: "",
    startEffecTime: new Date(),
    endEffecTime: new Date(),
    isEnable: 0,
  });
  let ruleInfoList = reactive<RuleInfo[]>([
    {
      id: "684684645680",
      ruleName: "规则1",
      scenariosKey: "场景1",
      condtitonDetail: [
        {
          fieldKey: "fieldKey",
          fieldName: "fieldName",
          fieldValueType: "fieldValueType",
          type: "type",
          fieldBasicType: "fieldBasicType",
          operator: "operator",
          targetValue: {
            valueType: "",
            single: {},
            range: {},
            list: {},
          },
        },
      ],
      resultDetail: [
        {
          fieldKey: "fieldKey",
          fieldName: "fieldName",
          fieldValueType: "fieldValueType",
          targetValue: "targetValue",
        },
      ],
      resultAction: "resultAction",
      description: "description",
      startEffecTime: new Date(),
      endEffecTime: new Date(),
      isEnable: 0,
    },
  ]);
  let conditionFieldList = reactive<FieldInfo[]>([]);
  let resultFieldList = reactive<FieldInfo[]>([]);
  let selectedConditionField = reactive<string[]>([]);
  let selectedResultField = reactive<string[]>([]);
  // 为介于和不介于操作符扩展conditionFieldConfigs对象，增加valueStart和valueEnd字段
  interface ConditionConfig {
    operator: string;
    value: string;
    valueStart?: string;
    valueEnd?: string;
    valueArray?: string[];
  }

  interface ResultConfig {
    operator: string;
    value: string;
    valueArray?: string[];
  }

  // 更新类型声明
  let conditionFieldConfigs = reactive<Record<string, ConditionConfig>>({});
  let resultFieldConfigs = reactive<Record<string, ResultConfig>>({});
  
  // 自动补全框查询函数
  function autoCompleteQuerySearch(queryString: string, cb: any) {
    console.log("自动补全框查询函数");
    console.log(JSON.stringify(ruleScenariosOptionList));
    console.log(queryString);
    let results = queryString
      ? ruleScenariosOptionList.filter(autoCompleteFilter(queryString))
      : ruleScenariosOptionList;
    // call callback function to return suggestions
    cb(results);
  }
  // 自动补全框过滤函数
  function autoCompleteFilter(queryString: string) {
    return (selectOption: SelectOption) => {
      return (
        selectOption.key.toLowerCase().indexOf(queryString.toLowerCase()) === 0
      );
    };
  }
  // 自动补全框选择事件
  function autoCompleteHandleSeletct(item: Record<string, any>) {
    console.log("autoCompleteHandleSeletct");
    console.log(JSON.stringify(item));
    // 查询规则场景信息
    getRuleScenariosByScenariosKey(item.key);
    // 查询规则场景下所有规则
    console.log("触发事件，查询规则场景下所有规则");
    let ruleQueryParams = reactive<RuleQueryParams>({
      ruleName: "",
      scenariosKey: item.key,
      isEnable: 0,
    });
    getRuleInfoByQueryParam(ruleQueryParams);
    console.log("自动补全框查询规则");
    console.log(JSON.stringify(ruleInfoList));
    
    // 加载字段列表
    loadConditionFields();
    loadResultFields();
  }

  // 根据查询条件获取规则信息
  async function getRuleInfoByQueryParam(params:RuleQueryParams) {
    console.log("根据查询条件获取规则信息")
    console.log(JSON.stringify(params))
    let result = await axios
      .post("/rule/select/ruleDisplay/byQuery", params)
      .then((res) => {
        if (res.data.code == 200) {
          console.log(JSON.stringify(res.data.content));
          ruleInfoList.length = 0;
          Object.assign(ruleInfoList, res.data.content);
        }
      });
  }

  // 根据规则场景key获取规则场景信息
  async function getRuleScenariosByScenariosKey(scenariosKey: string) {
    console.log("根据规则场景key获取规则场景信息");
    console.log(scenariosKey);
    let result = await axios
      .get("/ruleScenarios/get/ruleScenarios/by/" + scenariosKey)
      .then((res) => {
        if (res.data.code == 200) {
          Object.assign(ruleScenariosInfo, res.data.content);
        }
      });
  }
  // 自动补全框处理事件函数
  function actoCompleteHandleIconClick(event: Event) {
    console.log("actoCompleteHandleIconClick");
    console.log(event);
  }
  function loadRuleScenariosOptionList() {
    console.log("加载所有规则场景");
    getAllRuleScenariosOption();
  }
  // 获取所有规则场景
  async function getAllRuleScenariosOption() {
    try {
      let result = await axios.get(
        "/ruleScenarios/get/all/ruleScenarios/options"
      );
      console.log("获取自定义类型option集合");
      if (result.data.code == 200) {
        console.log(JSON.stringify(result.data.content));
        ruleScenariosOptionList.length = 0;
        Object.assign(ruleScenariosOptionList, result.data.content);
      }
    } catch (error) {
      console.log(error);
    }
  }
  // 根据查询条件获取规则
  async function searchRuleByQueryParam(params: RuleQueryParams) {
    console.log("根据查询条件获取规则");
    params.scenariosKey = ruleScenariosInfo.scenariosKey;
    console.log(JSON.stringify(params));
    // 参数校验
    let isIllegal = validateRuleQueryParams(params);
    if (isIllegal) {
      let result = await axios
        .post("/rule/select/ruleDisplay/byQuery", params)
        .then((res) => {
          if (res.data.code == 200) {
            console.log(JSON.stringify(res.data.content));
            ruleInfoList.length = 0;
            Object.assign(ruleInfoList, res.data.content);
          }
        });
    }
  }
  // 校验查询参数
  function validateRuleQueryParams(params: RuleQueryParams): boolean {
    if (params.scenariosKey == "") {
      ElMessage({
        type: "error",
        message: "请选择规则场景",
      });
      return false;
    }
    return true;
  }
  async function searchConditionFieldItem(params: string) {
    console.log("根据规则场景获取规则条件字段");
    console.log(params); // todo xpx 未完成
  }
  function getRuleInfo(index: number, row: RuleInfo) {
    console.log("获取规则详情");
    console.log(JSON.stringify(row));
    // todo 获取规则详情，可修改
  }
  // 根据id删除规则
  async function deleteRule(id: string) {
    console.log("删除规则");
    console.log(id);
    let result = await axios.get("/rule/delete/" + id).then((res) => {
      if (res.data.code == 200) {
        ElMessage({
          type: "success",
          message: "删除规则成功!",
        });
      } else {
        ElMessage({
          type: "error",
          message: res.data.msg,
        });
      }
    });
  }
  // 明细项分页处理页码
  function ruleHandleCurrentChange(param: number) {
    ruleCurrentPage.value = param;
  }
  // 明细项处理每页条数变化
  function ruleHandleSizeChange(param: number) {
    rulePageSize.value = param;
    ruleCurrentPage.value = 1;
  }
  // 打开新增规则窗口
  async function openRuleInsertWindow() {
    console.log("打开新增规则窗口");
    
    // 检查是否已选择规则场景
    if (!ruleScenariosInfo.scenariosKey) {
      ElMessage({
        type: "warning",
        message: "请先选择规则场景",
      });
      return;
    }
    
    // 获取规则场景下的条件字段集合及结果字段集合
    await axios
      .get(
        "/businessModel/get/fieldList/by/" +
          ruleScenariosInfo.conditionModelName
      )
      .then((res) => {
        console.log("获取规则场景下所有条件字段集合");
        if (res.data.code == 200) {
          conditionFieldList.length = 0;
          Object.assign(conditionFieldList, res.data.content);
          console.log("条件字段集合");
          console.log(JSON.stringify(conditionFieldList));
        }
      })
      .catch((error) => {
        console.error("获取条件字段失败:", error);
        // 添加一些测试数据，以便在接口失败时也能测试功能
        conditionFieldList.length = 0;
        conditionFieldList.push({
          modelKey: "test1",
          fieldName: "测试字段1",
          modelFieldName: "testField1",
          modelFieldZhName: "测试字段1",
          fieldValueType: "string",
          fieldType: "text",
          basicFieldType: "string",
        });
        conditionFieldList.push({
          modelKey: "test2",
          fieldName: "测试字段2",
          modelFieldName: "testField2",
          modelFieldZhName: "测试字段2",
          fieldValueType: "number",
          fieldType: "integer",
          basicFieldType: "string"
        });
        console.log("添加了测试条件字段数据");
      });
    await axios
      .get(
        "/businessModel/get/fieldList/by/" + ruleScenariosInfo.resultModelName
      )
      .then((res) => {
        console.log("获取规则场景下所有结果字段集合");
        if (res.data.code == 200) {
          resultFieldList.length = 0;
          Object.assign(resultFieldList, res.data.content);
          console.log("结果字段集合");
          console.log(JSON.stringify(resultFieldList));
        }
      });
    // 获取所有操作符
    await axios.get("/rule/get/all/operator").then((res) => {
      console.log("获取所有操作符");
      if (res.data.code == 200) {
        operatorList.length = 0;
        Object.assign(operatorList, res.data.content);
        console.log("操作符集合");
        console.log(JSON.stringify(operatorList));
      }
    });
    
    // 清空已选字段列表
    selectedConditionField.length = 0;
    selectedResultField.length = 0;
    
    // 清空表单数据
    insertRule.ruleName = "";
    insertRule.description = "";
    insertRule.resultAction = "";
    insertRule.startEffecTime = new Date();
    insertRule.endEffecTime = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000); // 默认30天后过期
    insertRule.isEnable = 0; // 默认启用
    
    // 打开窗口
    ruleInsertWindowsEnable.value = true;
  }
  // 提交新增规则
  async function insertRuleOnSubmit(params: RuleInfo) {
    console.log("提交新增规则");
    // 将配置的条件字段填充到insertRule的conditionDetail中
    // 创建新数组替代原来的数组，避免类型错误
    const conditionDetails: RuleConditionItemInfo[] = [];
    for (const fieldKey of selectedConditionField) {
      if (conditionFieldConfigs[fieldKey]) {
        // 查找该字段在conditionFieldList中的完整信息
        const fieldInfo = conditionFieldList.find(
          (item) => item.modelFieldName === fieldKey
        );
        if (fieldInfo) {
          conditionDetails.push({
            fieldKey: fieldKey, // 使用modelFieldName作为fieldKey
            fieldName: fieldInfo.modelFieldZhName || fieldInfo.fieldName, // 使用中文名称
            fieldValueType: fieldInfo.fieldValueType || "",
            type: fieldInfo.fieldType || "",
            fieldBasicType: fieldInfo.fieldValueType || "",
            operator: conditionFieldConfigs[fieldKey].operator || "",
            // targetValue: conditionFieldConfigs[fieldKey].value || "",
            targetValue: {
              valueType: "",
              single: {},
              range: {},
              list: {},
            },
          });
        }
      }
    }

    // 使用非空断言，确保至少有一个默认项
    if (conditionDetails.length === 0) {
      conditionDetails.push({
        fieldKey: "",
        fieldName: "",
        fieldValueType: "",
        type: "",
        fieldBasicType: "",
        operator: "",
        targetValue: {
          valueType: "",
          single: {},
          range: {},
          list: {},
        },
      });
    }

    // 使用类型断言解决类型问题
    insertRule.condtitonDetail = conditionDetails as [RuleConditionItemInfo];

    // 设置规则场景key
    insertRule.scenariosKey = ruleScenariosInfo.scenariosKey;

    console.log("提交的规则数据:", JSON.stringify(insertRule));

    // 进行数据校验
    if (insertRule.ruleName == "") {
      ElMessage({
        type: "error",
        message: "规则名称不能为空",
      });
      return;
    }
    if (conditionDetails.length === 1 && conditionDetails[0].fieldName === "") {
      ElMessage({
        type: "error",
        message: "条件明细不能为空，请至少添加一个条件字段",
      });
      return;
    }
    // 检查每个条件字段是否都填写了操作符和值
    const invalidCondition = conditionDetails.find(
      (item) => item.fieldName !== "" && (!item.operator || !item.targetValue)
    );
    if (invalidCondition) {
      ElMessage({
        type: "error",
        message: `条件字段 "${invalidCondition.fieldName}" 的操作符或条件值未填写完整`,
      });
      return;
    }

    // 发送数据到后端
    axios
      .post("/rule/insert", insertRule)
      .then((res) => {
        console.log(res.data);
        if (res.data.code === 200) {
          // 使用严格相等
          ElMessage({
            type: "success",
            message: "新增规则成功!",
          });
          ruleInsertWindowsEnable.value = false;
        } else {
          ElMessage({
            type: "error",
            message: res.data.msg,
          });
        }
      })
      .catch((error) => {
        console.error("提交规则失败", error);
        ElMessage({
          type: "error",
          message: "提交规则失败，请检查网络连接",
        });
      });
  }
  // 修改规则
  async function updateRuleOnSubmit(params: RuleInfo) {
    console.log("调用后端接口修改规则");
    console.log(JSON.stringify(params));
  }
  // 添加条件字段选择变更事件处理函数
  function handleConditionFieldChange(value: string[]) {
    console.log("选择的条件字段：", value);
    // 这里已经自动更新了selectedConditionField，因为它是通过v-model双向绑定的
  }
  // 加载条件字段
  function loadConditionFields() {
    console.log("加载条件字段");
    axios
      .get(
        "/businessModel/get/fieldList/by/" +
          ruleScenariosInfo.conditionModelName
      )
      .then((res) => {
        console.log("获取规则场景下所有条件字段集合");
        if (res.data.code == 200) {
          conditionFieldList.length = 0;
          Object.assign(conditionFieldList, res.data.content);
          console.log("条件字段集合");
          console.log(JSON.stringify(conditionFieldList));
          
          // 预加载所有枚举类型字段的选项
          conditionFieldList.forEach(field => {
            if (field.fieldValueType === 'enumConstant' && field.fieldType) {
              const constantKey = field.fieldType;
              if (!enumOptionsCache[constantKey]) {
                // 预加载枚举数据
                axios.get(`/constantItem/select/constantItem/by/${constantKey}`)
                  .then((result) => {
                    if (result.data.code === 200 && result.data.content) {
                      // 转换为选项格式
                      const options = result.data.content.map((item: any) => ({
                        value: item.itemKey,
                        label: item.itemName
                      }));
                      
                      // 更新缓存
                      enumOptionsCache[constantKey] = options;
                    }
                  })
                  .catch(error => {
                    console.error('预加载枚举选项失败:', error);
                  });
              }
            }
          });
        }
      })
      .catch((error) => {
        console.error("获取条件字段失败:", error);
        // 添加一些测试数据
        conditionFieldList.length = 0;
        conditionFieldList.push({
          modelKey: "test1",
          fieldName: "测试字段1",
          modelFieldName: "testField1",
          modelFieldZhName: "测试字段1(基本类型)",
          fieldValueType: "basicType",
          fieldType: "text",
          basicFieldType: "string",
        });
        conditionFieldList.push({
          modelKey: "test2",
          fieldName: "测试字段2",
          modelFieldName: "testField2",
          modelFieldZhName: "测试字段2(数值)",
          fieldValueType: "basicType",
          fieldType: "integer",
          basicFieldType: "integer",
        });
        conditionFieldList.push({
          modelKey: "test3",
          fieldName: "测试字段3",
          modelFieldName: "testField3",
          modelFieldZhName: "测试字段3(布尔值)",
          fieldValueType: "basicType",
          fieldType: "boolean",
          basicFieldType: "boolean",
        });
        conditionFieldList.push({
          modelKey: "qualification",
          fieldName: "学历",
          modelFieldName: "qualification",
          modelFieldZhName: "学历(枚举)",
          fieldValueType: "enumConstant",
          fieldType: "qualification",
          basicFieldType: "string",
        });
        
        // 初始化枚举数据
        enumOptionsCache["qualification"] = [
          { value: 'PRIMARY_SCHOOL', label: '小学' },
          { value: 'JUNIOR_HIGH_SCHOOL', label: '初中' },
          { value: 'SENIOR_HIGH_SCHOOL', label: '高中' },
          { value: 'VOCATIONAL_SCHOOL', label: '中专' },
          { value: 'ASSOCIATE_DEGREE', label: '大专' },
          { value: 'UNDERGRADUATE_DEGREE', label: '本科' },
          { value: 'GRADUATE_DEGREE', label: '硕士' },
          { value: 'DOCTORATE_DEGREE', label: '博士' }
        ];
        
        console.log("添加了测试条件字段数据");
      });
  }
  // 加载结果字段
  function loadResultFields() {
    console.log("加载结果字段");
    axios
      .get(
        "/businessModel/get/fieldList/by/" +
          ruleScenariosInfo.resultModelName
      )
      .then((res) => {
        console.log("获取规则场景下所有结果字段集合");
        if (res.data.code == 200) {
          resultFieldList.length = 0;
          Object.assign(resultFieldList, res.data.content);
          console.log("结果字段集合");
          console.log(JSON.stringify(resultFieldList));
          
          // 预加载所有枚举类型字段的选项
          resultFieldList.forEach(field => {
            if (field.fieldValueType === 'enumConstant' && field.fieldType) {
              const constantKey = field.fieldType;
              if (!enumOptionsCache[constantKey]) {
                // 预加载枚举数据
                axios.get(`/constantItem/select/constantItem/by/${constantKey}`)
                  .then((result) => {
                    if (result.data.code === 200 && result.data.content) {
                      // 转换为选项格式
                      const options = result.data.content.map((item: any) => ({
                        value: item.itemKey,
                        label: item.itemName
                      }));
                      
                      // 更新缓存
                      enumOptionsCache[constantKey] = options;
                    }
                  })
                  .catch(error => {
                    console.error('预加载枚举选项失败:', error);
                  });
              }
            }
          });
        }
      })
      .catch((error) => {
        console.error("获取结果字段失败:", error);
        // 添加一些测试数据
        resultFieldList.length = 0;
        resultFieldList.push({
          modelKey: "test1",
          fieldName: "测试字段1",
          modelFieldName: "testField1",
          modelFieldZhName: "测试字段1(基本类型)",
          fieldValueType: "basicType",
          fieldType: "text",
          basicFieldType: "string",
        });
        resultFieldList.push({
          modelKey: "test2",
          fieldName: "测试字段2",
          modelFieldName: "testField2",
          modelFieldZhName: "测试字段2(数值)",
          fieldValueType: "basicType",
          fieldType: "integer",
          basicFieldType: "integer",
        });
        resultFieldList.push({
          modelKey: "qualification",
          fieldName: "学历",
          modelFieldName: "qualification",
          modelFieldZhName: "学历(枚举)",
          fieldValueType: "enumConstant",
          fieldType: "qualification",
          basicFieldType: "string",
        });
        
        // 初始化枚举数据
        if (!enumOptionsCache["qualification"]) {
          enumOptionsCache["qualification"] = [
            { value: 'PRIMARY_SCHOOL', label: '小学' },
            { value: 'JUNIOR_HIGH_SCHOOL', label: '初中' },
            { value: 'SENIOR_HIGH_SCHOOL', label: '高中' },
            { value: 'VOCATIONAL_SCHOOL', label: '中专' },
            { value: 'ASSOCIATE_DEGREE', label: '大专' },
            { value: 'UNDERGRADUATE_DEGREE', label: '本科' },
            { value: 'GRADUATE_DEGREE', label: '硕士' },
            { value: 'DOCTORATE_DEGREE', label: '博士' }
          ];
        }
        
        console.log("添加了测试结果字段数据");
      });
  }
  // 获取字段的中文名称
  function getConditionFieldZhName(fieldKey: string): string {
    const field = conditionFieldList.find(
      (item) => item.modelFieldName === fieldKey
    );
    return field ? field.modelFieldZhName || field.fieldName : fieldKey;
  }
  // 获取结果字段的中文名称
  function getResultFieldZhName(fieldKey: string): string {
    const field = resultFieldList.find(
      (item) => item.modelFieldName === fieldKey
    );
    return field ? field.modelFieldZhName || field.fieldName : fieldKey;
  }
  // 添加条件字段
  function addConditionField(fieldKey: string) {
    if (!selectedConditionField.includes(fieldKey)) {
      selectedConditionField.push(fieldKey);
      // 初始化该字段的配置
      conditionFieldConfigs[fieldKey] = { operator: "", value: "" };
      console.log(`添加条件字段: ${fieldKey}`, selectedConditionField);
    }
  }
  // 添加结果字段
  function addResultField(fieldKey: string) {
    if (!selectedResultField.includes(fieldKey)) {
      selectedResultField.push(fieldKey);
      resultFieldConfigs[fieldKey] = { operator: "", value: "" };
      console.log(`添加结果字段: ${fieldKey}`, selectedResultField);
    }
  }
  // 修改函数参数名，使其更准确
  function removeConditionField(fieldKey: string) {
    const index = selectedConditionField.indexOf(fieldKey);
    if (index !== -1) {
      selectedConditionField.splice(index, 1);
      // 移除该字段的配置
      delete conditionFieldConfigs[fieldKey];
      console.log(`移除条件字段: ${fieldKey}`, selectedConditionField);
    }
  }
  // 修改函数参数名，使其更准确
  function removeResultField(fieldKey: string) {
    const index = selectedResultField.indexOf(fieldKey);
    if (index !== -1) {
      selectedResultField.splice(index, 1);
      // 移除该字段的配置
      delete resultFieldConfigs[fieldKey];
      console.log(`移除条件字段: ${fieldKey}`, selectedResultField);
    }
  }
  // 获取条件字段的操作符
  function getConditionOperator(fieldKey: string) {
    if (!conditionFieldConfigs[fieldKey]) {
      conditionFieldConfigs[fieldKey] = { operator: "", value: "" };
    }
    return conditionFieldConfigs[fieldKey].operator;
  }
  // 获取结果字段的操作符
  function getResultOperator(fieldKey: string) {
    if (!resultFieldConfigs[fieldKey]) {
      resultFieldConfigs[fieldKey] = { operator: "", value: "" };
    }
    return resultFieldConfigs[fieldKey].operator;
  }
  // 设置条件字段的操作符
  function setConditionOperator(fieldKey: string, operator: string) {
    if (!conditionFieldConfigs[fieldKey]) {
      conditionFieldConfigs[fieldKey] = { operator: "", value: "" };
    }
    conditionFieldConfigs[fieldKey].operator = operator;
  }
  // 设置结果字段的操作符
  function setResultOperator(fieldKey: string, operator: string) {
    if (!resultFieldConfigs[fieldKey]) {
      resultFieldConfigs[fieldKey] = { operator: "", value: "" };
    }
    resultFieldConfigs[fieldKey].operator = operator;
  }
  // 获取条件字段的值
  function getConditionValue(fieldKey: string) {
    if (!conditionFieldConfigs[fieldKey]) {
      conditionFieldConfigs[fieldKey] = { operator: "", value: "" };
    }
    return conditionFieldConfigs[fieldKey].value;
  }
  // 获取结果字段的值
  function getResultValue(fieldKey: string) {
    if (!resultFieldConfigs[fieldKey]) {
      resultFieldConfigs[fieldKey] = { operator: "", value: "" };
    }
    return resultFieldConfigs[fieldKey].value;
  }
  // 设置条件字段的值
  function setConditionValue(fieldKey: string, value: string) {
    if (!conditionFieldConfigs[fieldKey]) {
      conditionFieldConfigs[fieldKey] = { operator: "", value: "" };
    }
    conditionFieldConfigs[fieldKey].value = value;
  }
  // 设置条件字段的值
  function setResultValue(fieldKey: string, value: string) {
    if (!resultFieldConfigs[fieldKey]) {
      resultFieldConfigs[fieldKey] = { operator: "", value: "" };
    }
    resultFieldConfigs[fieldKey].value = value;
  }

  // 获取操作符
  function getOperator():Operator[] {
    return [
      {
        code: "null",
        zhName: "空值",
        aviatorExperssion: "is null",
        displayText: "为空",
      },
      {
        code: "notNull",
        zhName: "非空值",
        aviatorExperssion: "is not null",
        displayText: "不为空",
      },
      {
        code: "equal",
        zhName: "等于",
        aviatorExperssion: "==",
        displayText: "等于",
      },
      {
        code: "notEqual",
        zhName: "不等于",
        aviatorExperssion: "!=",
        displayText: "不等于",
      },
      {
        code: "greaterThan",
        zhName: "大于",
        aviatorExperssion: ">",
        displayText: "大于",
      },
      {
        code: "greaterThanOrEqual",
        zhName: "大于等于",
        aviatorExperssion: ">=",
        displayText: "大于等于",
      },
      {
        code: "lessThan",
        zhName: "小于",
        aviatorExperssion: "<",
        displayText: "小于",
      },
      {
        code: "lessThanOrEqual",
        zhName: "小于等于",
        aviatorExperssion: "<=",
        displayText: "小于等于",
      },
      {
        code: "between",
        zhName: "介于",
        aviatorExperssion: "between",
        displayText: "介于",
      },
      {
        code: "notBetween",
        zhName: "不介于",
        aviatorExperssion: "not between",
        displayText: "不介于",
      },
      {
        code: "contains",
        zhName: "包含",
        aviatorExperssion: "contains",
        displayText: "包含",
      },
      {
        code: "notContains",
        zhName: "不包含",
        aviatorExperssion: "not contains",
        displayText: "不包含",
      },
      {
        code: "in",
        zhName: "包含于",
        aviatorExperssion: "in",
        displayText: "属于",
      },
      {
        code: "notIn",
        zhName: "不包含于",
        aviatorExperssion: "not in",
        displayText: "不属于",
      },
      {
        code: "regex",
        zhName: "正则匹配",
        aviatorExperssion: "matches",
        displayText: "正则匹配于",
      }
    ]
  }

  // 获取字段的字段值类型
  function getFieldValueType(fieldKey: string): string {
    const field = conditionFieldList.find(
      (item) => item.modelFieldName === fieldKey
    );
    return field ? field.fieldValueType : 'basicType';
  }

  // 获取结果字段的字段值类型
  function getResultFieldValueType(fieldKey: string): string {
    const field = resultFieldList.find(
      (item) => item.modelFieldName === fieldKey
    );
    return field ? field.fieldValueType : 'basicType';
  }

  // 根据字段类型和字段值类型获取可用的操作符
  function getAvailableOperators(fieldKey: string): Operator[] {
    const fieldValueType = getFieldValueType(fieldKey);
    
    if (fieldValueType === 'basicType') {
      return [
        {
          code: "isEmpty",
          zhName: "为空",
          aviatorExperssion: "is null",
          displayText: "为空",
        },
        {
          code: "isNotEmpty",
          zhName: "不为空",
          aviatorExperssion: "is not null",
          displayText: "不为空",
        },
        {
          code: "equal",
          zhName: "等于",
          aviatorExperssion: "==",
          displayText: "等于",
        },
        {
          code: "notEqual",
          zhName: "不等于",
          aviatorExperssion: "!=",
          displayText: "不等于",
        },
        {
          code: "greaterThan",
          zhName: "大于",
          aviatorExperssion: ">",
          displayText: "大于",
        },
        {
          code: "greaterThanOrEqual",
          zhName: "大于等于",
          aviatorExperssion: ">=",
          displayText: "大于等于",
        },
        {
          code: "lessThan",
          zhName: "小于",
          aviatorExperssion: "<",
          displayText: "小于",
        },
        {
          code: "lessThanOrEqual",
          zhName: "小于等于",
          aviatorExperssion: "<=",
          displayText: "小于等于",
        },
        {
          code: "between",
          zhName: "介于",
          aviatorExperssion: "between",
          displayText: "介于",
        },
        {
          code: "notBetween",
          zhName: "不介于",
          aviatorExperssion: "not between",
          displayText: "不介于",
        },
        {
          code: "contains",
          zhName: "包含",
          aviatorExperssion: "contains",
          displayText: "包含",
        },
        {
          code: "notContains",
          zhName: "不包含",
          aviatorExperssion: "not contains",
          displayText: "不包含",
        },
        {
          code: "in",
          zhName: "属于",
          aviatorExperssion: "in",
          displayText: "属于",
        },
        {
          code: "notIn",
          zhName: "不属于",
          aviatorExperssion: "not in",
          displayText: "不属于",
        }
      ];
    } else if (fieldValueType === 'enumConstant') {
      return [
        {
          code: "isEmpty",
          zhName: "为空",
          aviatorExperssion: "is null",
          displayText: "为空",
        },
        {
          code: "isNotEmpty",
          zhName: "不为空",
          aviatorExperssion: "is not null",
          displayText: "不为空",
        },
        {
          code: "equal",
          zhName: "等于",
          aviatorExperssion: "==",
          displayText: "等于",
        },
        {
          code: "notEqual",
          zhName: "不等于",
          aviatorExperssion: "!=",
          displayText: "不等于",
        },
        {
          code: "in",
          zhName: "属于",
          aviatorExperssion: "in",
          displayText: "属于",
        },
        {
          code: "notIn",
          zhName: "不属于",
          aviatorExperssion: "not in",
          displayText: "不属于",
        }
      ];
    }
    
    // 默认返回所有操作符
    return getOperator();
  }

  // 获取枚举选项
  const enumOptionsCache = reactive<Record<string, any[]>>({});

  function getEnumOptions(fieldKey: string): any[] {
    console.log("getEnumOptions调用，fieldKey:", fieldKey);
    
    const field = conditionFieldList.find(
      (item) => item.modelFieldName === fieldKey
    );
    
    if (!field || field.fieldValueType !== 'enumConstant') {
      return [];
    }
    
    const constantKey = field.fieldType;
    
    // 如果缓存中已经有数据，直接返回
    if (enumOptionsCache[constantKey]) {
      return enumOptionsCache[constantKey];
    } else {
      // 初始化缓存为默认数据
      const defaultOptions = [
        { value: 'loading', label: '加载中...' }
      ];
      enumOptionsCache[constantKey] = defaultOptions;
      
      // 异步获取数据并更新缓存
      axios.get(`/constantItem/select/constantItem/by/${constantKey}`)
        .then((result) => {
          if (result.data.code === 200 && result.data.content) {
            // 转换为选项格式
            const options = result.data.content.map((item: any) => ({
              value: item.itemKey,
              label: item.itemName
            }));
            
            // 更新缓存
            enumOptionsCache[constantKey] = options;
          }
        })
        .catch((error) => {
          console.error('获取枚举选项失败:', error);
          // 添加测试数据
          enumOptionsCache[constantKey] = [
            { value: 'option1', label: '选项1' },
            { value: 'option2', label: '选项2' },
            { value: 'option3', label: '选项3' }
          ];
        });
      
      return enumOptionsCache[constantKey];
    }
  }

  // 获取结果枚举选项
  function getResultEnumOptions(fieldKey: string): any[] {
    const field = resultFieldList.find(
      (item) => item.modelFieldName === fieldKey
    );
    
    if (!field || field.fieldValueType !== 'enumConstant') {
      return [];
    }
    
    const constantKey = field.fieldType;
    
    // 如果缓存中已经有数据，直接返回
    if (enumOptionsCache[constantKey]) {
      return enumOptionsCache[constantKey];
    } else {
      // 初始化缓存为默认数据
      const defaultOptions = [
        { value: 'loading', label: '加载中...' }
      ];
      enumOptionsCache[constantKey] = defaultOptions;
      
      // 异步获取数据并更新缓存
      axios.get(`/constantItem/select/constantItem/by/${constantKey}`)
        .then((result) => {
          if (result.data.code === 200 && result.data.content) {
            // 转换为选项格式
            const options = result.data.content.map((item: any) => ({
              value: item.itemKey,
              label: item.itemName
            }));
            
            // 更新缓存
            enumOptionsCache[constantKey] = options;
          }
        })
        .catch((error) => {
          console.error('获取枚举选项失败:', error);
          // 添加测试数据
          enumOptionsCache[constantKey] = [
            { value: 'option1', label: '选项1' },
            { value: 'option2', label: '选项2' },
            { value: 'option3', label: '选项3' }
          ];
        });
      
      return enumOptionsCache[constantKey];
    }
  }

  // 介于/不介于操作符的起始值
  function getConditionValueStart(fieldKey: string): string {
    if (!conditionFieldConfigs[fieldKey]) {
      conditionFieldConfigs[fieldKey] = { operator: "", value: "" };
    }
    return conditionFieldConfigs[fieldKey].valueStart || "";
  }

  // 介于/不介于操作符的结束值
  function getConditionValueEnd(fieldKey: string): string {
    if (!conditionFieldConfigs[fieldKey]) {
      conditionFieldConfigs[fieldKey] = { operator: "", value: "" };
    }
    return conditionFieldConfigs[fieldKey].valueEnd || "";
  }

  // 设置介于/不介于操作符的起始值
  function setConditionValueStart(fieldKey: string, value: string): void {
    if (!conditionFieldConfigs[fieldKey]) {
      conditionFieldConfigs[fieldKey] = { operator: "", value: "" };
    }
    conditionFieldConfigs[fieldKey].valueStart = value;
    // 同时更新value字段，用于数据提交
    updateConditionValue(fieldKey);
  }

  // 设置介于/不介于操作符的结束值
  function setConditionValueEnd(fieldKey: string, value: string): void {
    if (!conditionFieldConfigs[fieldKey]) {
      conditionFieldConfigs[fieldKey] = { operator: "", value: "" };
    }
    conditionFieldConfigs[fieldKey].valueEnd = value;
    // 同时更新value字段，用于数据提交
    updateConditionValue(fieldKey);
  }

  // 更新条件值
  function updateConditionValue(fieldKey: string): void {
    const config = conditionFieldConfigs[fieldKey];
    if (!config) return;

    const operator = config.operator;
    
    if (operator === 'between' || operator === 'notBetween') {
      config.value = `${config.valueStart || ''},${config.valueEnd || ''}`;
    } else if (operator === 'in' || operator === 'notIn') {
      config.value = (config.valueArray || []).join(',');
    }
  }

  // 获取属于/不属于操作符的多选值
  function getConditionValueArray(fieldKey: string): string[] {
    if (!conditionFieldConfigs[fieldKey]) {
      conditionFieldConfigs[fieldKey] = { operator: "", value: "" };
    }
    return conditionFieldConfigs[fieldKey].valueArray || [];
  }

  // 设置属于/不属于操作符的多选值
  function setConditionValueArray(fieldKey: string, values: string[]): void {
    if (!conditionFieldConfigs[fieldKey]) {
      conditionFieldConfigs[fieldKey] = { operator: "", value: "" };
    }
    conditionFieldConfigs[fieldKey].valueArray = values;
    // 同时更新value字段，用于数据提交
    updateConditionValue(fieldKey);
  }

  // 获取结果明细的多选值
  function getResultValueArray(fieldKey: string): string[] {
    if (!resultFieldConfigs[fieldKey]) {
      resultFieldConfigs[fieldKey] = { operator: "", value: "" };
    }
    return resultFieldConfigs[fieldKey].valueArray || [];
  }

  // 设置结果明细的多选值
  function setResultValueArray(fieldKey: string, values: string[]): void {
    if (!resultFieldConfigs[fieldKey]) {
      resultFieldConfigs[fieldKey] = { operator: "", value: "" };
    }
    resultFieldConfigs[fieldKey].valueArray = values;
    // 同时更新value字段，用于数据提交
    resultFieldConfigs[fieldKey].value = values.join(',');
  }

  return {
    // autoCompleteRuleScenariosKey,
    ruleScenariosInfo,
    ruleScenariosOptionList,
    ruleQueryParams,
    ruleInsertWindowsEnable,
    ruleInfoList,
    ruleCurrentPage,
    rulePageSize,
    conditionFieldList,
    resultFieldList,
    insertRule,
    updateRule,
    selectedConditionField,
    selectedResultField,
    selectedConditionFieldWindowsEnable,
    autoCompleteQuerySearch,
    autoCompleteHandleSeletct,
    actoCompleteHandleIconClick,
    loadRuleScenariosOptionList,
    searchRuleByQueryParam,
    searchConditionFieldItem,
    getRuleInfo,
    deleteRule,
    ruleHandleSizeChange,
    ruleHandleCurrentChange,
    openRuleInsertWindow,
    insertRuleOnSubmit,
    updateRuleOnSubmit,
    handleConditionFieldChange,
    loadConditionFields,
    loadResultFields,
    addConditionField,
    addResultField,
    removeConditionField,
    getConditionOperator,
    setConditionOperator,
    getConditionValue,
    setConditionValue,
    conditionFieldConfigs,
    getConditionFieldZhName,
    getResultFieldZhName,
    getResultOperator,
    setResultOperator,
    setResultValue,
    getResultValue,
    removeResultField,
    getOperator,
    // 新增的方法
    getFieldValueType,
    getResultFieldValueType,
    getAvailableOperators,
    getEnumOptions,
    getResultEnumOptions,
    getConditionValueStart,
    getConditionValueEnd,
    setConditionValueStart,
    setConditionValueEnd,
    getConditionValueArray,
    setConditionValueArray,
    getResultValueArray,
    setResultValueArray,
  };
}
